ELEVATOR_CHANNEL = 1
ELEVATOR_FLOORS_CHANNEL = 2

modem = peripheral.wrap("left")	
modem.open(ELEVATOR_CHANNEL)

monitor = peripheral.wrap("right")
monitor.setCursorBlink(false)

function setLevel(level)
	modem.transmit(ELEVATOR_FLOORS_CHANNEL, ELEVATOR_FLOORS_CHANNEL, tostring(level))
end

function updateDisplay(monitor, level)
	monitor.setBackgroundColor(colors.black)
	monitor.setTextColor(colors.white)
	monitor.clear()
		
	for i=0, 3 do
		monitor.setCursorPos(2, i * 4 + 1)
		if level == (4 - i) then
			monitor.setBackgroundColor(colors.green)
			monitor.setTextColor(colors.black)
		else
			monitor.setBackgroundColor(colors.blue)
			monitor.setTextColor(colors.black)
		end
		monitor.write("     ")
		monitor.setCursorPos(2, i * 4 + 2)
		monitor.write("  "..tostring(4 - i).."  ")
		monitor.setCursorPos(2, i * 4 + 3)
		monitor.write("     ")
	end
	monitor.setCursorPos(2, 17)
	if level == 0 then
		monitor.setBackgroundColor(colors.green)
		monitor.setTextColor(colors.black)
	else
		monitor.setBackgroundColor(colors.blue)
		monitor.setTextColor(colors.black)
	end
	monitor.write("     ")
	monitor.setCursorPos(2, 18)
	monitor.write(" PB  ")
	monitor.setCursorPos(2, 19)
	monitor.write("     ")
end

function main()
	local level = 8
	updateDisplay(monitor, level)
	
	while true do
		event, param1, param2, param3, param4, param5 = os.pullEvent()
		if event == "modem_message" then
			local new_level = tonumber(param4)
			if 0 <= new_level and new_level <= 4 then
				level = new_level
				updateDisplay(monitor, level)
			end
		elseif event == "monitor_touch" then
			param3 = param3 - 1
			if (param3 % 4) ~= 0 and param3 <= 20 then
				setLevel(4 - math.floor(param3 / 4))
			end
		end
	end
end

main()
modem.close(ELEVATOR_CHANNEL)
